//
//  WBNewFeatureView.swift
//  Weibo
//
//  Created by niqiang on 16/7/11.
//  Copyright © 2016年 niqiang. All rights reserved.
//

import UIKit

class WBNewFeatureView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var enterButton: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
   
    // 进入微博
    @IBAction func enterStatus() {
        removeFromSuperview()
    }
    
    class func newFeatureView() -> WBNewFeatureView {
        let nib = UINib(nibName: "WBNewFeatureView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatureView
        
        v.frame = UIScreen.main().bounds
        
        return v
        
    }
    
    override func awakeFromNib() {
        //使用自动布局设置界面，从XIB加载默认是600*600 大小
        //添加4个图像视图
        let count = 4
        let rect = UIScreen.main().bounds
        
        for i in 0..<count {
            let imageName = "new_feature_\(i+1)"
            let iv = UIImageView(image: UIImage(named: imageName))
            
            //设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            
            scrollView.addSubview(iv)
            
            
        }
        //指定scrollview的属性 --- 实现滚动
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        
        //关闭弹簧效果
        scrollView.bounces = false
        //允许分页滚动   默认不会分页滚动即滚动到哪里页面就停在哪里
        scrollView.isPagingEnabled = true
        //关闭垂直，水平的滚动指示条
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        
        scrollView.delegate = self
        
        //隐藏“进入微博”按钮
        enterButton.isHidden = true
    }

}

extension WBNewFeatureView: UIScrollViewDelegate {
 
    //滚动视图结束调用方法 will---将要  did---完成
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //1滚动到最后一屏让视图删除  Int--强转
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
    //2判断是否是最后一页
        if page == scrollView.subviews.count {
        print("欢迎")
            removeFromSuperview()
        }
        //3.如果是倒数第二页，显示按钮
        enterButton.isHidden = (page != scrollView.subviews.count - 1)
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        //0.一旦滚动隐藏按钮
        enterButton.isHidden = true
        
        //1.计算当前偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        
        //2.设置分页控件
        pageControl.currentPage = page
        
        //3.分页控件的隐藏 @@@
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
}
